import useStore from "@/hooks/useStore";
import { apiGet } from "@/utils/request";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export default defineStore(
  "cinema",
  () => {
    // city - cityStore
    const { city } = useStore();

    // 影院列表数据
    const list = ref<ICinema[]>([]);

    // 基于 list -> 区县列表数据
    const districtList = computed(() => {
      const result: IDistrict[] = [];

      list.value.forEach((item) => {
        if (!result.find((dis) => dis.districtId === item.districtId)) {
          // 不存在，添加进去
          result.push({
            districtId: item.districtId,
            districtName: item.districtName,
          });
        }
      });

      // 头部添加一个全城
      result.unshift({
        districtId: -1,
        districtName: "全城",
      });

      return result;
    });

    // 当前选择的区县Id
    const curDisId = ref(-1);
    // 当前选择的区县对象
    const curDis = computed(() => {
      return districtList.value.find(
        (item) => item.districtId === curDisId.value
      );
    });
    const setCurDisId = (id: number) => {
      curDisId.value = id;
    };

    // 用于展示的影院列表数据，基于 list 与 curDisId
    const displayList = computed(() => {
      if (curDisId.value === -1) {
        // 全城
        return list.value;
      }

      return list.value.filter((item) => item.districtId === curDisId.value);
    });

    // 获取影院列表数据
    const getCinemaList = async (ticketFlag = 1) => {
      const resp = await apiGet<{
        cinemas: ICinema[];
      }>("mall.film-ticket.cinema.list", {
        cityId: city.selectedCity.cityId,
        ticketFlag,
      });

      list.value = resp.cinemas;
    };

    // 搜索历史记录
    const searchList = ref<{ id: number; name: string }[]>([]);
    // 添加历史记录
    const addSearch = (cinema: ICinema) => {
      // 不能添加同一个影院
      if (searchList.value.find((item) => item.id === cinema.cinemaId)) {
        return;
      }

      searchList.value.unshift({
        id: cinema.cinemaId,
        name: cinema.name,
      });

      searchList.value.splice(5);
    };
    // 删除历史记录
    const delSearch = (id: number) => {
      searchList.value = searchList.value.filter((item) => item.id !== id);
    };
    const clearSearch = () => {
      searchList.value = [];
    };

    return {
      list,
      districtList,
      curDisId,
      curDis,
      displayList,
      searchList,
      addSearch,
      delSearch,
      clearSearch,
      setCurDisId,
      getCinemaList,
    };
  },
  {
    persist: {
      paths: ["searchList"],
    },
  }
);
